package cn.wolfcode.trip.admin.controller;

import cn.wolfcode.trip.base.domain.News;
import cn.wolfcode.trip.base.domain.NewsContent;
import cn.wolfcode.trip.base.query.NewsQuery;
import cn.wolfcode.trip.base.service.INewsService;
import cn.wolfcode.trip.base.util.JsonResult;
import cn.wolfcode.trip.base.util.UploadUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

/**
 * 日报资源后台控制器
 */
@Controller
@RequestMapping("news")
public class NewsController {

    @Autowired
    private INewsService newsService;

    /**
     * 草稿日报页面
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("list")
    public String list(@ModelAttribute("qo") NewsQuery qo, Model model){
        if(qo.getState()==null) {
            //待审核状态
            qo.setState(News.STATE_AUDIT);
        }
        //创建时间升序
        qo.setOrderBy("releaseTime desc");
        model.addAttribute("pageInfo",newsService.query(qo));
        return "news/list";
    }

    /**
     * 已发布日报页面
     * @param qo
     * @param model
     * @return
     */
    @RequestMapping("releaseList")
    public String releaseList(@ModelAttribute("qo") NewsQuery qo, Model model){
        //待审核状态
        qo.setState(News.STATE_RELEASE);
        //创建时间升序
        qo.setOrderBy("releaseTime desc");
        model.addAttribute("pageInfo",newsService.query(qo));
        return "news/releaseList";
    }


    /**
     * 根据id查询日报内容
     * @param id
     * @return
     */
    @RequestMapping("getContentById")
    @ResponseBody
    public NewsContent getContentById(Long id){
        return newsService.getContentById(id);
    }

    /**
     * 修改日报状态
     * @param news
     * @return
     */
    @RequestMapping("updateState")
    @ResponseBody
    public JsonResult updateState(News news){
        newsService.updateState(news);
        return new JsonResult();
    }

    /**
     * 新增/修改
     * @param news
     * @param file
     * @return
     */
    @RequestMapping("saveOrUpdate")
    @ResponseBody
    public JsonResult saveOrUpdate(News news, MultipartFile file){
        if(file!=null&&file.getSize()>0){
            String url = UploadUtil.uploadQiniu(file);
            news.setCoverUrl(url);
        }
        newsService.saveOrUpdate(news);
        return new JsonResult();
    }
}
